package tools

import (
	"encoding/json"
	"fmt"
	"mcp-clarification-service/internal/protocol"
	"time"

	"github.com/google/uuid"
)

// Handler 工具处理器
type Handler struct {
	registry   *Registry
	dispatcher *Dispatcher
	timeout    time.Duration
}

// NewHandler 创建新的工具处理器
func NewHandler(registry *Registry, dispatcher *Dispatcher, timeout time.Duration) *Handler {
	return &Handler{
		registry:   registry,
		dispatcher: dispatcher,
		timeout:    timeout,
	}
}

// HandleToolCall 处理工具调用
func (h *Handler) HandleToolCall(toolName string, params json.RawMessage) (*protocol.ToolResult, error) {
	// 验证工具存在
	if _, ok := h.registry.Get(toolName); !ok {
		return nil, fmt.Errorf("tool not found: %s", toolName)
	}

	// 创建调用
	invocation := &ToolInvocation{
		ID:         uuid.New().String(),
		ToolName:   toolName,
		Params:     params,
		ResponseCh: make(chan *protocol.ToolResult, 1),
		ErrorCh:    make(chan error, 1),
	}

	if h.timeout > 0 {
		invocation.Deadline = time.Now().Add(h.timeout)
	}

	// 入队
	if err := h.dispatcher.Enqueue(invocation); err != nil {
		return nil, fmt.Errorf("failed to enqueue: %w", err)
	}

	// 等待响应
	if h.timeout <= 0 {
		select {
		case result := <-invocation.ResponseCh:
			return result, nil
		case err := <-invocation.ErrorCh:
			return nil, err
		}
	}

	timer := time.NewTimer(h.timeout)
	defer timer.Stop()

	select {
	case result := <-invocation.ResponseCh:
		return result, nil
	case err := <-invocation.ErrorCh:
		return nil, err
	case <-timer.C:
		return nil, fmt.Errorf("timeout")
	}
}

// ListTools 列出所有工具
func (h *Handler) ListTools() []protocol.ToolDefinition {
	return h.registry.List()
}
